import { createSlice } from '@reduxjs/toolkit';

// 初始状态
const initialState = {
  token: localStorage.getItem('token') || null, // 初始化时从 localStorage 读取 token
  isAuthenticated: false,
};

// 创建 authSlice
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setToken: (state, action) => {
      state.token = action.payload;
      state.isAuthenticated = true;
      localStorage.setItem('token', action.payload); // 存储 token 到 localStorage
    },
    removeToken: (state) => {
      state.token = null;
      state.isAuthenticated = false;
      localStorage.removeItem('token'); // 移除 token
    },
  },
});

// 导出 action 和 reducer
export const { setToken, removeToken } = authSlice.actions;
export default authSlice.reducer;
